package com.example.woke1;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.bigkoo.alertview.AlertView;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.woke.data.Data_nearbyperson;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.wokeMy.view.base.BaseActivity;
import com.wokeMy.view.model.Constant;
import com.wokeMy.view.model.YxListEvent;
import com.wokeMy.view.util.Util;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import cn.xl.xxl.imagecache.ImageLoader;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class NearbyfriendActivity extends BaseActivity implements AMapLocationListener, OnItemClickListener,EasyPermissions.PermissionCallbacks {

	private static final int LOCATION_PHONE_STORAGE = 12;
	private ListView mListView;
	private MyApp application;
	private ArrayList<Data_nearbyperson> datalist = new ArrayList<Data_nearbyperson> ();
	private RelativeLayout mBar;
	private ImageLoader imageLoader;

	private AMapLocationClient locationClient = null;
	private AMapLocationClientOption locationOption = null;

	private String gaodeweidu;
	private String gaodejingdu;
	private Nearbyadater adapter;
	private double longitude;
	private double latitude;

	private Datas_load loaded;

	Dialog  dialog;

	AlertView mAlertViewExt;
	EditText etName;
	String word="";
	int type=0;

	@Override
	public void setContentView() {
		setContentView (R.layout.activity_nearbyfriend);

	}
	@Override
	public void initView() {
		imageLoader = new ImageLoader (this);
		application = (MyApp) getApplication ();
		intview ();
	}

	@Override
	public void initData() {

	}

	@Override
	public void initActivity() {

	}

	private void sendjinweidu(String latitude, String longitude) {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (NearbyfriendActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "nearbyList");
		params.put ("userid", application.getDatas_load ().getId ());
		params.put ("lat", latitude);
		params.put ("lng", longitude);//γ��
		params.put ("range", "50000");
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				Log.e ("福建", response.toString ());
				try {
					String flag = response.getString ("flag");
					if (flag.equals ("success")) {
						JSONObject object = response.getJSONObject ("data");
						String string = object.getString ("data");
						ArrayList<Data_nearbyperson> parseArray = (ArrayList<Data_nearbyperson>) com.alibaba.fastjson.JSONArray
								.parseArray (string, Data_nearbyperson.class);
						datalist.addAll (parseArray);
						adapter.notifyDataSetChanged ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
			}

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mBar.setVisibility (View.GONE);
			}
		});
	}

	class Nearbyadater extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datalist.size ();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		public class Holder {
			TextView username;
			ImageView yaoqing;
			ImageView icon;
			TextView juli;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {

			Holder holder = null;
			if (convertView == null) {
				holder = new Holder ();
				convertView = getLayoutInflater ().inflate (R.layout.item_friend_forf, null);
				holder.username = (TextView) convertView.findViewById (R.id.item_friden_textname);
				holder.yaoqing = (ImageView) convertView.findViewById (R.id.item_friden_result);
				holder.icon = (ImageView) convertView.findViewById (R.id.avuserinfo_image_inco);
				holder.juli = (TextView) convertView.findViewById (R.id.item_friden_textinfo);
				convertView.setTag (holder);
			} else {
				holder = (Holder) convertView.getTag ();
			}
			final Data_nearbyperson nearbyperson = datalist.get (position);
			holder.username.setText (nearbyperson.getName ());
			holder.juli.setText ("");
//			imageLoader.DisplayImage ("http://" + nearbyperson.getAvatar (), holder.icon, false, true, true, 0);
//			final String status = nearbyperson.getStatus ();
			holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right2));
//			if (status.equals ("1")) {
//				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right3));
//			} else if (status.equals ("2")) {
//				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_right2));
//			} else if (status.equals ("3")) {
//				holder.yaoqing.setImageDrawable (getResources ().getDrawable (R.drawable.avphonef_agree3));
//			}

			holder.yaoqing.setOnClickListener (new OnClickListener () {

				@Override
				public void onClick(View v) {
					dialog=Util.createLoadingDialog(NearbyfriendActivity.this);
					addyxFrend(nearbyperson.getUser_id());
//					if (status.equals ("1")) {
////						Toast.makeText(NearbyfriendActivity.this, "���޷�����", Toast.LENGTH_SHORT).show();
//					} else if (status.equals ("2")) {
//						addsomeone (datalist.get (position).getId (), position);
//					}
				}
			});

			return convertView;
		}
	}

	private void addsomeone(String substring, final int position) {
		if(application.getDatas_load ()==null)return;
		AsyncHttpClient ahc = new AsyncHttpClient ();
		PersistentCookieStore myCookieStore = new PersistentCookieStore (NearbyfriendActivity.this);
		ahc.setCookieStore (myCookieStore);
		RequestParams params = new RequestParams ();
		params.put ("g", "api");
		params.put ("m", "user");
		params.put ("a", "addNearby");
		params.put ("userid", application.getDatas_load ().getId ());//��ǰ�û�id
		params.put ("touserid", substring);
		ahc.get (HttpMethods.BASEURL, params, new JsonHttpResponseHandler () {
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess (statusCode, headers, response);
				try {
					String flag = response.getString ("flag");
					String info = response.getString ("info");
					if (flag.equals ("success")) {
						Toast.makeText (NearbyfriendActivity.this, "" + info, Toast.LENGTH_SHORT)
								.show ();
//						datalist.get (position).setStatus ("3");
						adapter.notifyDataSetChanged ();
					} else {
						Toast.makeText (NearbyfriendActivity.this, "" + info, Toast.LENGTH_SHORT)
								.show ();
					}
				} catch (JSONException e) {
					e.printStackTrace ();
				}
			}

			@Override
			public void onFailure(int statusCode, Header[] headers,
					String responseString, Throwable throwable) {
				super.onFailure (statusCode, headers, responseString, throwable);
				Log.e ("responseString", "d" + responseString);
			}

			@Override
			public void onStart() {
				super.onStart ();
				mBar.setVisibility (View.VISIBLE);
			}

			@Override
			public void onFinish() {
				super.onFinish ();
				mBar.setVisibility (View.GONE);
			}
		});
	}

	private void intview() {
		findViewById (R.id.avnearbyf_image_back).setOnClickListener (new OnClickListener () {
			@Override
			public void onClick(View v) {
				finish ();
			}
		});
		findViewById(R.id.textView1_search).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mAlertViewExt = new AlertView("搜索", null, "取消", null, new String[]{"完成"}, NearbyfriendActivity.this, AlertView.Style.Alert, new com.bigkoo.alertview.OnItemClickListener() {
					@Override
					public void onItemClick(Object o, int position) {
						mAlertViewExt.dismiss();
						if (position==0){
							word=etName.getText().toString().trim();
							dialog=Util.createLoadingDialog(NearbyfriendActivity.this);
							getYunxunListAble();

						}
					}
				});
				ViewGroup extView = (ViewGroup) LayoutInflater.from(NearbyfriendActivity.this).inflate(R.layout.alertext_form, null);
				etName = (EditText) extView.findViewById(R.id.etName);
				mAlertViewExt.addExtView(extView);
				mAlertViewExt.show();
			}
		});

		mBar = (RelativeLayout) findViewById (R.id.avnearby_progress_bar);
		mListView = (ListView) findViewById (R.id.avnearbyf_listview);
		mListView.setOnItemClickListener (this);
		adapter = new Nearbyadater ();
		mListView.setAdapter (adapter);
		dialog= Util.createLoadingDialog(this);
		getYunxunListAble();
//
//		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//			methodRequiresTwoPermission ();
//		} else {
//
//			initAMap ();//获取到权限
//		}
//		mHandler.sendEmptyMessage(Utils.MSG_LOCATION_START);
	}

	@AfterPermissionGranted(LOCATION_PHONE_STORAGE)
	private void methodRequiresTwoPermission() {
		String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION,
				Manifest.permission.ACCESS_COARSE_LOCATION,
				Manifest.permission.READ_PHONE_STATE};
		if (EasyPermissions.hasPermissions (this, perms)) {
			// Already have permission, do the thing
			// ...
			initAMap ();//获取到权限
		} else {
			// Do not have permissions, request them now
			EasyPermissions.requestPermissions (this, "应用需要定位您的位置",
					LOCATION_PHONE_STORAGE, perms);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
		super.onRequestPermissionsResult (requestCode, permissions, grantResults);
		EasyPermissions.onRequestPermissionsResult (requestCode, permissions, grantResults, this);
	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {
		if (requestCode == LOCATION_PHONE_STORAGE) {
			initAMap ();
		}
	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {
		if (requestCode == LOCATION_PHONE_STORAGE) {
			new AlertDialog.Builder (this).setMessage ("请在<权限管理>里打开定位权限")
					.setPositiveButton ("前往", new DialogInterface.OnClickListener () {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent (Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
							intent.setData (Uri.fromParts ("package", getPackageName (), null));
							startActivity (intent);
							dialog.dismiss ();
						}
					})
					.setNegativeButton ("取消", null)
					.create ()
					.show ();
		}
	}

	private void initAMap() {
		locationClient = new AMapLocationClient (this.getApplicationContext ());
		locationOption = new AMapLocationClientOption ();
		locationOption.setLocationMode (AMapLocationMode.Hight_Accuracy);
		locationClient.setLocationListener (this);
		locationOption.setOnceLocation (true);
		locationClient.setLocationOption (locationOption);
		locationClient.startLocation ();
	}

	@Override
	protected void onDestroy() {
		imageLoader.clearCache ();
		imageLoader.clearMemoryCache ();
		super.onDestroy ();
	}

	public String getmapresult(AMapLocation location) {
		if (null == location) {
			return null;
		}
		StringBuffer sb = new StringBuffer ();
		if (location.getErrorCode () == 0) {
			sb.append ("定位成功" + "\n");
			sb.append ("定位类型: " + location.getLocationType () + "\n");
			sb.append ("经    度    : " + location.getLongitude () + "\n");
			longitude = location.getLongitude ();
			gaodejingdu = "" + location.getLongitude ();
			sb.append ("纬    度    : " + location.getLatitude () + "\n");
			latitude = location.getLatitude ();
			gaodeweidu = "" + location.getLatitude ();
			sb.append ("精    度    : " + location.getAccuracy () + "米 " + "\n");
			sb.append ("提供者    : " + location.getProvider () + "\n");

			if (location.getProvider ().equalsIgnoreCase (
					android.location.LocationManager.GPS_PROVIDER)) {
				// ������Ϣֻ���ṩ����GPSʱ�Ż���
				sb.append ("速    度    : " + location.getSpeed () + "��/��" + "\n");
				sb.append ("角    度    : " + location.getBearing () + "\n");
				// ��ȡ��ǰ�ṩ��λ��������Ǹ���
				sb.append ("星    数    : "
						+ location.getSatellites () + "\n");
			} else {
				// �ṩ����GPSʱ��û��������Ϣ��
				sb.append ("国    家    : " + location.getCountry () + "\n");
				sb.append ("省            : " + location.getProvince () + "\n");
				sb.append ("市            : " + location.getCity () + "\n");
				sb.append ("城市编码 : " + location.getCityCode () + "\n");
				sb.append ("区            : " + location.getDistrict () + "\n");
				sb.append ("区域 码   : " + location.getAdCode () + "\n");
				sb.append ("地    址    : " + location.getAddress () + "\n");
				sb.append ("兴趣点   : " + location.getPoiName () + "\n");
			}
		} else {
			//��λʧ��
			sb.append ("定位失败" + "\n");
			sb.append ("错误码:" + location.getErrorCode () + "\n");
			sb.append ("错误信息:" + location.getErrorInfo () + "\n");
			sb.append ("错误描述:" + location.getLocationDetail () + "\n");
			Log.e ("123", sb.toString ());
			Toast.makeText (this, "定位失败！", Toast.LENGTH_LONG).show ();
		}

		if (! gaodejingdu.equals ("") && ! gaodeweidu.equals ("")) {
			sendjinweidu (gaodejingdu, gaodeweidu);
		}

		return sb.toString ();
	}

	@Override
	public void onLocationChanged(AMapLocation loc) {
		if (null != loc) {
			AMapLocation loc1 = loc;
			String result = getmapresult (loc1);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//		Intent intent = new Intent (NearbyfriendActivity.this, GaodemapActivity.class);
//		intent.putExtra ("longitude", datalist.get (arg2).lat);
//		intent.putExtra ("latitude", datalist.get (arg2).lng);
//		intent.putExtra ("user_nicename", datalist.get (arg2).user_nicename);
//		intent.putExtra ("data", datalist);
//		startActivity (intent);
	}

	// 获取可以添加列表
	public void getYunxunListAble() {
		loaded=application.getDatas_load();
		AsyncHttpClient ahc = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("user_id",loaded.getId());
		params.put("word",word);
		Log.e("获取可以添加列表 params",params.toString());
		Log.e("获取可以添加列表 url", Constant.YXFRIENDLISADDABLET_URL);
		//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
		ahc.post(Constant.YXFRIENDLISADDABLET_URL, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				Util.closeDialog(dialog);
				//判断状态码
				if(i == 200){
					//获取结果
					try {
						String result = new String(bytes, "utf-8");
						//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
						Log.e("获取可以添加列表 Result", result);
						try {
							datalist.clear();
							JSONObject jsonObject = new JSONObject(result);
							if (jsonObject.getString("flag").equals("success")){
									if(jsonObject.has("data")){
										JSONObject object = jsonObject.getJSONObject ("data");
										String string = object.getString ("data");
										ArrayList<Data_nearbyperson> parseArray = (ArrayList<Data_nearbyperson>) com.alibaba.fastjson.JSONArray
												.parseArray (string, Data_nearbyperson.class);
										for (int i1 = 0; i1 < parseArray.size(); i1++) {
											if (loaded.getId().equals(parseArray.get(i1).getUser_id())){
												parseArray.remove(i1);
											}

										}
										datalist.addAll (parseArray);
									}
									adapter.notifyDataSetChanged ();

							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
				Util.closeDialog(dialog);
				Toast.makeText(NearbyfriendActivity.this,"请求失败",Toast.LENGTH_SHORT).show();
				Log.e("onFailure",new String(bytes).toString());
			}
		});
	}


	//添加云信好友

	public void addyxFrend(String to_user_id ) {
		loaded=application.getDatas_load();
		AsyncHttpClient ahc = new AsyncHttpClient();
		RequestParams params = new RequestParams();
		params.put("user_id",loaded.getId());
		params.put("to_user_id",to_user_id);
		Log.e("添加云信好友 params",params.toString());
		Log.e("添加云信好友 url", Constant.YXFADDFREND_URL);
		//url:   parmas：请求时携带的参数信息   responseHandler：是一个匿名内部类接受成功过失败
		ahc.post(Constant.YXFADDFREND_URL, params, new AsyncHttpResponseHandler() {
			@Override
			public void onSuccess(int i, Header[] headers, byte[] bytes) {
				Util.closeDialog(dialog);
				//判断状态码
				if(i == 200){
					//获取结果
					try {
						String result = new String(bytes, "utf-8");
						//                        Toast.makeText(CreditRepayActivity.this, result, Toast.LENGTH_SHORT).show();
						Log.e("添加云信好友 Result", result);
						try {
							JSONObject jsonObject = new JSONObject(result);
							String infro=jsonObject.getString("info");
							if (jsonObject.getString("flag").equals("success")){
								tishiToast("已经发送");
								YxListEvent yxListEvent=new YxListEvent();
								EventBus.getDefault().post(yxListEvent);
								datalist.clear();
								getYunxunListAble();
								return;
							}
							tishi(infro);
						} catch (JSONException e) {
							e.printStackTrace();
						}

					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}

			@Override
			public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
				Util.closeDialog(dialog);
				tishi("请求失败");
				Log.e("onFailure",new String(bytes).toString());
			}
		});
	}

}
